package com.ocom.mqsimple.business.faceerr;

import com.alibaba.fastjson.JSON;
import com.ocom.common.utils.DateUtil;
import com.ocom.common.vo.pay.FaceErrVo;
import com.ocom.mqsimple.config.FaceErrConfig;
import com.ocom.mqsimple.feign.PayhandleClientService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Component
public class FaceErrConsumerMqListener {

	private Logger logger = LoggerFactory.getLogger(FaceErrConsumerMqListener.class);


	@Autowired
	private PayhandleClientService payhandleClientService;




	/**
	 * 把该监听命名为A监听
	 * 监听队列  远程服务支付接口发送消息  该队列会接受
	 * [message, headers, channel]
	 * @return {@link }
	 * @throws
	 */
	@RabbitListener(queues = FaceErrConfig.FACE_ERR_QUEUE)
	public void process(Message message, @Headers Map<String, Object> headers, Channel channel) throws Exception {

		Integer hour = DateUtil.getHour(new Date());
		List<Integer> upto = new ArrayList<>();
		upto.add(7);
		upto.add(8);
		upto.add(11);
		upto.add(12);
		upto.add(17);
		upto.add(18);
		upto.add(19);
		if(upto.contains(hour)){
			channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
			return;
		}

		logger.info("faceErr 消费中");
		logger.info("message【{}】",message);
		String humanMessage = new String(message.getBody(), StandardCharsets.UTF_8);
		//TODO 数据库操作样例
		logger.info("faceErr-start:【{}】",humanMessage);
		logger.info("System.currentTimeMillis()【{}】",System.currentTimeMillis());

		FaceErrVo faceErrVo = JSON.parseObject(humanMessage, FaceErrVo.class);

		try {
			payhandleClientService.faceErrRecode(faceErrVo);
		} catch (Exception e) {
			logger.info("faceErr-出现异常队列消息开始进入死信队列{{}}",e);
		}

		channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
		logger.info("faceErr-end:【{}】",humanMessage);
		logger.info("System.currentTimeMillis()【{}】",System.currentTimeMillis());
	}

	/**
	 * 把该监听命名为B监听
	 * 监听死信队列  远程服务支付接口发送消息  该队列会接受
	 * [message, headers, channel]
	 * @return {@link }
	 * @throws
	 */
	@RabbitListener(queues =  FaceErrConfig.FACE_ERR_DIE_QUEUE)
	public void processForDie(Message message, @Headers Map<String, Object> headers, Channel channel) throws Exception {
		//死信队列放弃
		channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
		logger.info("人臉失敗-死信队列放弃 ， 【{}】",message);
	}


}
